package com.yoomiito.app.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * EditText和删除按钮 Button  TextView 交互
 * 获取EditText的内容
 */
public class EditTextUtil {

    private EditText mEditText;
    private Button mButton;
    private ImageView mImageView;
    private int mNumberLength;
    private int mLength;
    private boolean mCancelLength = true;
    private boolean phoneType = false;
    public EditTextUtil(EditText editText, Button button) {
        this.mEditText = editText;
        this.mButton = button;

    }

    public void setEditTextListener() {
        if (mTextWatcher != null) {
            mEditText.setText("");
            mEditText.addTextChangedListener(mTextWatcher);
        }
    }

    public void setEditTextListener1() {
        if (mTextWatcher != null) {
            mEditText.addTextChangedListener(mTextWatcher);
        }
    }

    public void deleteTextWatcher() {
        if (mTextWatcher != null) {
            mButton.setEnabled(false);
            mEditText.removeTextChangedListener(mTextWatcher);
        }
    }

    public void setNumberLength(int numberLength) {
        mNumberLength = numberLength;
    }

    public void setIvDelete(ImageView imageView) {
        mImageView = imageView;
    }

    public void cancelLength() {

    }

    private void setButtonEnabled() {
        if (mLength >= mNumberLength) {

            mButton.setEnabled(true);
//            if (mImageView != null) {
//                mImageView.setVisibility(View.VISIBLE);
//            }
        } else {
            mButton.setEnabled(false);
        }
        if (mImageView != null) {
            if (mLength == 0) {
                if (mImageView != null)
                    mImageView.setVisibility(View.GONE);
            } else {
                if (mImageView != null)
                    mImageView.setVisibility(View.VISIBLE);
            }
        }
    }

    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str = s.toString();
            mLength = str.length();
            setButtonEnabled();
        }
    };

    public String getPhoneText() {
        String str = mEditText.getText().toString().trim();
        return str.replace(" ","");
    }
}
